<?php

namespace App\Admin\Models;

use ClassesWithParents\D;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Encore\Admin\Controllers\AuthController;
use phpqrcode;

//class Users extends Authenticatable
class Users extends Model
{
    use Notifiable;

    protected $table = 'users';
    const USER_STATUS_DEFAULT = 2;
    const USER_STATUS_REFUSE = 3;
    const USER_STATUS_SUCCESS = 4;

    public static function boot()
    {
        parent::boot();
        static::saving(function ($model) {
            $account = $model['account'];
            $level = $model['level'];
//            if($level == '0'){
//                return back()->with(admin_toastr($account.$level, 'error'));
//            }
            if(DB::table('users')->where('account',$account)->update(['level'=>$level])){
                if($account){
                    $user_info = DB::table('users')->where('account',$account)->first();
                    $h5_index = env('APP_URL') . "/h5";
                    $basic_url = $h5_index."?first_uid=".$user_info->id;

                    $img_info = DB::table("backgroud")->orderBy('id', 'desc')->first();
                    $img_background = $img_info? $img_info->value: "";

                    // 生成二维码图片
                    $qrc = get_qrcodes($basic_url, date("Ymdhis"), $img_background);
                    if ( !$qrc ){
                        $qrc = '';
                    }
                } else {
                    $qrc = '';
                }

                $admin_user['username'] = $model['admin_name'];
                $admin_user['name'] = $model['admin_name'];
                $admin_user['password'] = bcrypt($model['admin_pass']);
                $admin_user['account'] = $account;
                $admin_user['avatar'] = '/vendor/laravel-admin/AdminLTE/dist/img/user2-160x160.jpg';
                $admin_user['created_at'] = date('Y-m-d H:i:s',time());

                $admin_user['qr_code'] = $qrc;

                if(DB::table('admin_users')->insert($admin_user)){
                    $id = DB::getPdo()->lastInsertId();
                    $role_user['user_id'] = intval($id);
                    $role_user['created_at'] = date('Y-m-d H:i:s',time());
                    $role_user['role_id'] = 4;
                    DB::table('admin_role_users')->insert($role_user);
                }else{
                    return back()->with(admin_toastr('后端登录账户创建失败', 'error'));
                }
            }
        });
    }

    public function Parent()
    {
        return $this->belongsToMany('App\Admin\Models\Users', 'user_relation', 'user_id', 'pid');
    }
}
